package com.yuntianshi.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yuntianshi.common.PageResult;
import com.yuntianshi.common.RedisConstant;
import com.yuntianshi.config.MinioConfig;
import com.yuntianshi.dao.OrderDao;
import com.yuntianshi.dao.SetmealDao;
import com.yuntianshi.pojo.Setmeal;
import com.yuntianshi.service.SetmealService;
import com.yuntianshi.utils.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 体检套餐服务实现类
 */
@Service
@Transactional
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig prop;

    //新增套餐
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if(checkgroupIds != null && checkgroupIds.length > 0){
            //绑定套餐和内容组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic){
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }

    //绑定套餐和内容组的多对多关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        if (queryString!=null&&queryString.length()>0){
            PageHelper.startPage(1,pageSize);
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }


    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }


    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //根据套餐id查询内容组Id，查询中间关系表
    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        return setmealDao.findCheckGroupIdsBySetmealId(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //编辑套餐，同时需要更新和内容组的关联关系
        setmealDao.deleteAssociation(setmeal.getId());
        //向中间表(t_setmeal_checkgroup)插入数据（建立内容组和内容项关联关系）
        setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        // 更新套餐基本信息
        setmealDao.edit(setmeal);
        //图片更新至redis
        savePic2Redis(setmeal.getImg());
    }

    @Override
    public void delete(Integer id) {
        //删除套餐与内容项关联关系
        setmealDao.deleteAssociation(id);
        //删除套餐与订单关联关系
        orderDao.deleteBySetmealId(id);
        //删除套餐基本信息
        setmealDao.delete(id);
    }

//    @Scheduled(cron = "${time.cron}")
    public void scheduledDeleteImg(){
        //求差集
        Set<String> difference = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        boolean remove = minioUtils.remove(difference, prop.getBucketName2());
        if (remove){
            log.info("定时垃圾清理成功");
            //清除redis数据
            for (String fileName : difference) {
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            }
        }else {
            log.info("定时垃圾清理失败");
        }
    }


}
